package com.weayer.remote;

import com.weayer.constant.AmapConfigConstants;
import com.weayer.dto.ResponseResult;
import com.weayer.response.ServiceResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @description: 调用服务管理Client
 * @author: Weayer
 **/
@Service
public class MapServiceClient {
    @Value("${amap.key}")
    private String amapKey;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @Description: 创建服务
     * @Param: [name]
     * @return: com.weayer.dto.ResponseResult<com.weayer.response.ServiceResponse>
     **/
    public ResponseResult<ServiceResponse> add(String name){
        // 1. 组装url:
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstants.SERVICE_ADD_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key=" + amapKey);
        urlBuilder.append("&");
        urlBuilder.append("name=" + name);
        // 2. 调用高德地图api
        ResponseEntity<String> serviceEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        // 3. 解析接口
        return parseServiceEntity(serviceEntity.getBody());
    }
    public ResponseResult<ServiceResponse> parseServiceEntity(String serviceString){
        /***
         * {
         *     "code": 1,
         *     "message": "success",
         *     "data": {
         *         "name": "wei0",
         *         "sid": 1023154
         *     }
         * }

         * {
         *     "errcode": 10000,
         *     "errmsg": "OK",
         *     "data": {
         *         "count": 1,
         *         "results": [
         *             {
         *                 "name": "车辆终端",
         *                 "tid": 856006877,
         *                 "desc": "猎鹰轨迹服务-终端管理",
         *                 "createtime": 1710158679551,
         *                 "locatetime": 0
         *             }
         *         ]
         *     }
         * }
         **/
        JSONObject result = JSONObject.fromObject(serviceString);
        JSONObject data = result.getJSONObject("data");
        ServiceResponse serviceResponse = new ServiceResponse();
        serviceResponse.setName(data.getString("name"));
        serviceResponse.setSid(data.getString("sid"));
        return ResponseResult.success(serviceResponse);
    }
}
